<template>
  <view class="container">
    <view class="header">
      <!-- <text class="title">人生调色板</text> -->
      <view class="birth-year-selector">
        <text>出生年份：</text>
        <input type="number" v-model="birthYear" class="year-input" />
        <!-- <button @click="generateLifeGrid" class="update-btn">更新</button> -->
      </view>
    </view>

    <view class="legend">
      <view
        class="legend-item"
        v-for="(item, index) in customPhases"
        :key="index"
      >
        <view
          class="color-block"
          :style="{ backgroundColor: item.color }"
        ></view>
        <text>{{ item.label }} ({{ formatYearMonth(item.startYear, item.startMonth) }}-{{ formatYearMonth(item.endYear, item.endMonth) }})</text>
      </view>
    </view>

    <view class="life-grid">
      <view
        class="grid-row"
        v-for="(row, rowIndex) in gridRows"
        :key="rowIndex"
      >
        <view
          class="grid-cell"
          v-for="(cell, cellIndex) in row"
          :key="cellIndex"
        >
          <view class="year-label">{{ cell.year }}</view>
          <view class="month-grid">
            <view
              class="month-cell"
              v-for="(month, monthIndex) in cell.months"
              :key="monthIndex"
              @click="showMonthInfo(cell.year, monthIndex + 1)"
            >
              <view 
                class="month-overlay"
                v-for="(overlay, overlayIndex) in month.overlays"
                :key="overlayIndex"
                :style="{ backgroundColor: overlay.color, width: overlay.width, left: overlay.left }"
              ></view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="phase-management">
      <view class="section-title">人生阶段管理</view>
      <view class="phase-form">
        <input v-model="newPhase.label" placeholder="阶段名称例如:工作" class="form-input" />
        <view class="form-row">
          <input v-model.number="newPhase.startYear" type="number" placeholder="起始年份例如:2010" class="form-input small" />
          <input v-model.number="newPhase.startMonth" type="number" placeholder="起始月份例如:5" class="form-input small" min="1" max="12" />
        </view>
        <view class="form-row">
          <input v-model.number="newPhase.endYear" type="number" placeholder="结束年份例如:2020" class="form-input small" />
          <input v-model.number="newPhase.endMonth" type="number" placeholder="结束月份例如:10" class="form-input small" min="1" max="12" />
        </view>
        <view class="color-picker">
          <!-- 生成五十个常用的颜色板，以便用户选择 -->
          <view class="color-palette">
    <view class="palette-title">常用颜色</view>
    <view class="palette-grid">
      <view 
        class="color-item" 
        v-for="(color, index) in commonColors" 
        :key="index"
        :style="{ backgroundColor: color }"
        @click="selectColor(color)"
      ></view>
    </view>
  </view>
         <input v-model="newPhase.color" type="color" class="color-input" />
          <view class="color-preview"  :style="{ backgroundColor: newPhase.color }"></view>
         
        </view>
        <button @click="addPhase" class="add-btn">添加阶段</button>
      </view>
      
      <view class="existing-phases">
        <view 
          class="phase-item" 
          v-for="(phase, index) in customPhases" 
          :key="index"
        >
          <view class="phase-info">
            <view class="color-indicator" :style="{ backgroundColor: phase.color }"></view>
            <text>{{ phase.label }} ({{ formatYearMonth(phase.startYear, phase.startMonth) }}-{{ formatYearMonth(phase.endYear, phase.endMonth) }})</text>
          </view>
          <button @click="removePhase(index)" class="remove-btn">删除</button>
        </view>
      </view>
    </view>

    <view class="year-info" v-if="selectedYearInfo">
      <text class="info-title">{{ selectedYearInfo.year }}年详情</text>
      <view class="months-detail">
        <view 
          class="month-detail" 
          v-for="(month, index) in selectedYearInfo.months" 
          :key="index"
        >
          <text class="month-number">{{ index + 1 }}月:</text>
          <view class="month-phases">
            <text
              v-for="(phase, phaseIndex) in month.phases"
              :key="phaseIndex"
              class="phase-tag"
              :style="{ backgroundColor: phase.color }"
            >
              {{ phase.label }}
            </text>
          </view>
        </view>
      </view>
    </view>
    <view class="summary-section">
      <view class="section-title">人生阶段统计</view>
      <view class="summary-item" v-for="(item, index) in summaryData" :key="index">
        <view class="summary-label">
          <view class="color-indicator" :style="{ backgroundColor: item.color }"></view>
          <text>{{ item.label }}</text>
        </view>
        <text class="summary-value">{{ item.percentage }}% ({{ item.months }}月)</text>
      </view>
    </view>

    <!-- <t-color-picker
      ref="colorPickerMy"
      :color="choseColor"
      @confirm="confirmMy"
    ></t-color-picker> -->
  </view>
</template>

<script>
// import tColorPicker from "@/components/t-color-picker/t-color-picker.vue";
export default {
  // components: {
  //   tColorPicker,
  // },
  data() {
    return {
      birthYear: 2001,
      gridRows: [],
      // 用户自定义人生阶段
      customPhases: [
        // {
        //   startYear: 2001,
        //   startMonth: 1,
        //   endYear: 2007,
        //   endMonth: 12,
        //   label: "童年",
        //   color: "rgba(255, 153, 153, 0.7)",
        // },
        // {
        //   startYear: 2008,
        //   startMonth: 1,
        //   endYear: 2014,
        //   endMonth: 12,
        //   label: "小学",
        //   color: "rgba(255, 204, 153, 0.7)",
        // },
        // {
        //   startYear: 2015,
        //   startMonth: 1,
        //   endYear: 2017,
        //   endMonth: 12,
        //   label: "初中",
        //   color: "rgba(255, 255, 153, 0.7)",
        // },
        // {
        //   startYear: 2018,
        //   startMonth: 1,
        //   endYear: 2020,
        //   endMonth: 12,
        //   label: "高中",
        //   color: "rgba(204, 255, 153, 0.7)",
        // },
        {
          startYear: 2021,
          startMonth: 1,
          endYear: 2024,
          endMonth: 12,
          label: "大学(示例)",
          color: "rgba(153, 255, 153, 0.7)",
        },
        // {
        //   startYear: 2025,
        //   startMonth: 1,
        //   endYear: 2061,
        //   endMonth: 12,
        //   label: "工作",
        //   color: "rgba(153, 255, 255, 0.7)",
        // }
      ],
      // choseColor: { r: 255, g: 0, b: 0, a: 0.6 },
      commonColors: [
      '#FF0000', '#FF4500', '#FF8C00', '#FFD700', '#FFFF00',
      '#ADFF2F', '#7CFC00', '#00FF00', '#32CD32', '#00FA9A',
      '#00FFFF', '#00BFFF', '#1E90FF', '#4169E1', '#0000FF',
      '#8A2BE2', '#9400D3', '#FF1493', '#FF69B4', '#FFB6C1',
      '#8B4513', '#A0522D', '#D2691E', '#CD853F', '#DAA520',
      '#B8860B', '#32CD32', '#8FBC8F', '#20B2AA', '#48D1CC',
      '#40E0D0', '#00CED1', '#5F9EA0', '#6495ED', '#4682B4',
      '#191970', '#8B008B', '#9932CC', '#8B0000', '#A52A2A',
      '#B22222', '#DC143C', '#FF6347', '#FF7F50', '#FFA500',
      '#FFDAB9', '#FFE4B5', '#FFFACD', '#F5FFFA', '#F8F8FF'
    ],
      newPhase: {
        startYear:null ,
        startMonth: null,
        endYear: null,
        endMonth: null,
        label: '',
        color: '#FF0000'
      },
      selectedYearInfo: null,
      summaryData: []
    };
  },

  watch: {
    birthYear: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.generateLifeGrid();
        }
      },
      immediate: true,
    },
    customPhases: {
      handler() {
        this.generateLifeGrid();
        this.calculateSummary();
      },
      deep: true
    }
  },

  mounted() {
    this.calculateSummary();
  },

  methods: {
    generateLifeGrid() {
      const rows = [];
      const gridSize = 10; // 10x10网格表示100年

      for (let i = 0; i < gridSize; i++) {
        const row = [];
        for (let j = 0; j < gridSize; j++) {
          const year = parseInt(this.birthYear) + (i * gridSize + j);
          const months = [];
          
          // 为每个月份计算颜色
          for (let m = 1; m <= 12; m++) {
            months.push({
              overlays: this.getMonthOverlays(year, m)
            });
          }
          
          row.push({
            year: year,
            months: months
          });
        }
        rows.push(row);
      }

      this.gridRows = rows;
      this.selectedYearInfo = null;
      this.calculateSummary();
    },

    getMonthOverlays(year, month) {
      const overlays = [];
      let index = 0;
      const matchingPhases = [];
      
      // 找到所有匹配的阶段
      this.customPhases.forEach(phase => {
        if (this.isMonthInPhase(year, month, phase)) {
          matchingPhases.push(phase);
        }
      });
      
      // 为每个匹配的阶段创建overlay
      matchingPhases.forEach(phase => {
        // 计算每个overlay的宽度和位置以实现重叠效果
        const width = `${100 / matchingPhases.length}%`;
        const left = `${(index * 100 / matchingPhases.length)}%`;
        
        overlays.push({
          color: phase.color,
          width: width,
          left: left
        });
        
        index++;
      });
      
      // 如果没有阶段，添加默认背景
      if (overlays.length === 0) {
        overlays.push({
          color: "#f0f0f0",
          width: "100%",
          left: "0%"
        });
      }
      
      return overlays;
    },

    isMonthInPhase(year, month, phase) {
      const startTotalMonths = phase.startYear * 12 + phase.startMonth;
      const endTotalMonths = phase.endYear * 12 + phase.endMonth;
      const currentTotalMonths = year * 12 + month;
      
      return currentTotalMonths >= startTotalMonths && currentTotalMonths <= endTotalMonths;
    },

    showMonthInfo(year, month) {
      // 显示整年的信息
      const months = [];
      
      for (let m = 1; m <= 12; m++) {
        const phases = [];
        
        // 收集该月份的所有阶段
        this.customPhases.forEach(phase => {
          if (this.isMonthInPhase(year, m, phase)) {
            phases.push({
              label: phase.label,
              color: phase.color
            });
          }
        });
        
        months.push({
          phases: phases
        });
      }
      
      this.selectedYearInfo = {
        year: year,
        months: months
      };
    },

    formatYearMonth(year, month) {
      return `${year}.${month.toString().padStart(2, '0')}`;
    },

    addPhase() {
      if (!this.newPhase.label) {
        uni.showToast({
          title: '请输入阶段名称',
          icon: 'none'
        });
        return;
      }
 //判断是否输入起始年份和月份
 if (!this.newPhase.startYear || !this.newPhase.startMonth) {
        uni.showToast({
          title: '请选择起始年份和月份',
          icon: 'none'
        });
        return;
      }

      if (!this.newPhase.endYear || !this.newPhase.endMonth) {
        uni.showToast({
          title: '请选择结束年份和月份',
          icon: 'none'
        });
        return;
      }
      
      if (this.newPhase.startYear > this.newPhase.endYear || 
          (this.newPhase.startYear === this.newPhase.endYear && this.newPhase.startMonth > this.newPhase.endMonth)) {
        uni.showToast({
          title: '起始时间不能大于结束时间',
          icon: 'none'
        });
        return;
      }
      
      this.customPhases.push({ ...this.newPhase });
      
      // 重置表单
      this.newPhase = {
        startYear:null ,
        startMonth: null,
        endYear: null,
        endMonth: null,
        label: '',
        color: '#FF0000'
      };
      
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      });
    },

    removePhase(index) {
      this.customPhases.splice(index, 1);
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      });
    },
    selectColor(color) {
    this.newPhase.color = color;
  },
    calculateSummary() {
      const summary = [];
      const totalMonths = 100 * 12; // 100年的人生，按月份计算

      // 统计自定义阶段
      this.customPhases.forEach(phase => {
        const startTotalMonths = phase.startYear * 12 + phase.startMonth;
        const endTotalMonths = phase.endYear * 12 + phase.endMonth;
        const birthStartTotalMonths = parseInt(this.birthYear) * 12 + 1;
        const birthEndTotalMonths = (parseInt(this.birthYear) + 99) * 12 + 12;
        
        const actualStart = Math.max(startTotalMonths, birthStartTotalMonths);
        const actualEnd = Math.min(endTotalMonths, birthEndTotalMonths);
        
        if (actualStart <= actualEnd) {
          const months = actualEnd - actualStart + 1;
          const percentage = Math.round((months / totalMonths) * 100);
          
          summary.push({
            label: phase.label,
            color: phase.color,
            months: months,
            percentage: percentage
          });
        }
      });

      this.summaryData = summary;
    }
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
  max-width: 750rpx;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.birth-year-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20rpx;
  gap: 10rpx;
}

.year-input {
  border: 1rpx solid #ccc;
  border-radius: 10rpx;
  padding: 10rpx 20rpx;
  width: 150rpx;
  text-align: center;
}

.update-btn {
  padding: 10rpx 20rpx;
  background-color: #007aff;
  color: white;
  border-radius: 10rpx;
  border: none;
}

.legend {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 30rpx;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
  margin-bottom: 10rpx;
}

.color-block {
  width: 30rpx;
  height: 30rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
  border: 1rpx solid #eee;
}

.life-grid {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.grid-row {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}

.grid-cell {
  width: 140rpx;
  height: 140rpx;
  border: 1rpx solid #ddd;
  margin: 5rpx;
  border-radius: 8rpx;
  position: relative;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column; /* 确保子元素垂直排列 */
}

.year-label {
  text-align: center;
  font-size: 24rpx;
  font-weight: bold;
  padding: 5rpx 0;
  color: #333;
  background-color: #fff; /* 背景颜色与 .month-cell 一致 */
  border-bottom: 1rpx solid #ddd; /* 分隔线 */
}

.month-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 2rpx;
  padding: 5rpx;
  height: calc(100% - 30rpx); /* 确保高度合理 */
  width: 100%; /* 宽度占满整个 .grid-cell */
  box-sizing: border-box; /* 包含 padding 在内 */
}

.month-cell {
  border-radius: 2rpx;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fff; /* 默认背景颜色 */
}

.month-overlay {
  position: absolute;
  top: 0;
  left: 0; /* 确保左对齐 */
  width: 100%; /* 宽度为 100% */
  height: 100%;
}

.summary-section {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
  padding: 10rpx;
  background-color: white;
  border-radius: 8rpx;
}

.summary-label {
  display: flex;
  align-items: center;
}

.color-indicator {
  width: 20rpx;
  height: 20rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
}

.summary-value {
  font-weight: bold;
}

.phase-management {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.phase-form {
  margin-bottom: 30rpx;
}

.form-input {
  width: 100%;
  /* padding: 15rpx; */
  margin-bottom: 15rpx;
  border: 1rpx solid #ccc;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.form-row {
  display: flex;
  gap: 15rpx;
}

.form-input.small {
  flex: 1;
  width: auto;
}

.color-picker {
 
  margin-bottom: 15rpx;
}
.color-palette {
  margin: 15rpx 0;
}

.palette-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.palette-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 10rpx;
}

.color-item {
  width: 40rpx;
  height: 40rpx;
  border-radius: 8rpx;
  border: 1rpx solid #eee;
  cursor: pointer;
}

.color-item:active {
  transform: scale(0.9);
}
.color-input {
  width: 200rpx;
  height: 60rpx;
  border: none;
  background: none;
}

.color-preview {
  width: 30rpx;
  height: 30rpx;
  border-radius: 4rpx;
  margin-left: 10rpx;
  border: 1rpx solid #ccc;
}

.add-btn {
  width: 100%;
  padding: 15rpx;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
}

.existing-phases {
  margin-top: 20rpx;
}

.phase-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx;
  background-color: white;
  border-radius: 8rpx;
  margin-bottom: 10rpx;
}

.phase-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.phase-info text {
  font-size: 24rpx;
}

.remove-btn {
  padding: 8rpx 16rpx;
  background-color: #ff3b30;
  color: white;
  border: none;
  border-radius: 6rpx;
  font-size: 24rpx;
  white-space: nowrap;
}

.year-info {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.info-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.months-detail {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.month-detail {
  display: flex;
  align-items: flex-start;
}

.month-number {
  width: 120rpx;
  font-weight: bold;
  color: #333;
}

.month-phases {
  display: flex;
  flex-wrap: wrap;
  flex: 1;
}

.phase-tag {
  color: white;
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  font-size: 24rpx;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .grid-cell {
    width: 120rpx;
    height: 120rpx;
  }
  
  .year-label {
    font-size: 20rpx;
  }
  
  .month-grid {
    gap: 1rpx;
    padding: 3rpx;
    height: calc(100% - 25rpx);
  }
  
  .legend {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .legend-item {
    width: 100%;
    margin-right: 0;
  }
}
</style>